package com.yf.aclient.service;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.yf.aclient.R;
import com.yf.aclient.notification.MyNotificationMgr;
import com.yf.aclient.threads.UploadThread;
/**
 * 
 *暂时弃用。。
 * @author yufei
 *
 */
@Deprecated
public class UploadService extends Service {

	// private String uploadActionUrl = "";
	private static NotificationManager mNotificationManager;

	private Map<String, Integer> map;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// uploadActionUrl=getString(R.string.serverUrl)+"/UploadSevelet";
		map = new HashMap<String, Integer>();
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				try {
					String info = (String) msg.obj;
					JSONObject jso = new JSONObject(info);
					Intent intent = new Intent(
							"broadcastReceiver.UploadBroadcastReceiver");
					intent.putExtra("info", jso.getString("fileName") + "上传成功");
					sendBroadcast(intent);
					int nid = map.get(jso.getString("nid"));
					String finish=URLDecoder.decode(jso.getString("nid"));
					new MyNotificationMgr(mNotificationManager,
							getBaseContext(), R.drawable.upload, "上传完成",
							finish+"上传完成！", true, nid);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		};
		// We want this service to continue running until it is explicitly
		// stopped, so return sticky.
		Toast.makeText(getBaseContext(), "上传服务启动", Toast.LENGTH_LONG).show();
		Bundle b = intent.getExtras();
		String[] urls = (String[]) b.get("data");
		String type = (String) b.get("type");
		String memo = (String) b.get("memo");
		int notification = b.getInt("notificationId");
		for (String url : urls) {
			if (!url.equals("")) {
				notification++;
				UploadThread thread = new UploadThread(url,memo, type,
						getString(R.string.serverUrl), handler);
				thread.start();
				map.put(URLEncoder.encode(url), notification);
				// int i=Math
				new MyNotificationMgr(mNotificationManager, getBaseContext(),
						R.drawable.upload, "文件上传", "正在上传"+url, true, notification);
			}
			// uploadFile(url,type);
		}
		// 上传完成后关闭自己。。
		// this.stopSelf();
		return START_STICKY;
	}

	public void onDestroy() {
		Toast.makeText(getBaseContext(), "上传服务关闭", Toast.LENGTH_LONG).show();
	}
}
